<template>
	<view id="app">
		<!-- 路由视图 -->
		<router-view></router-view>

		<!-- 底部导航栏 -->
		<view class="tab-bar" v-if="showTabBar">
			<view class="tab-item" v-for="tab in tabs" :key="tab.path" :class="{ active: currentPath === tab.path }"
				@click="switchTab(tab.path)">
				<view class="tab-icon">{{ tab.icon }}</view>
				<text class="tab-text">{{ tab.text }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		wechatAPI,
		userAPI
	} from './utils/api.js'
	export default {
		data() {
			return {
				currentPath: '/index',
				tabs: [{
						path: '/index',
						text: '对话',
						icon: '💬'
					},
					{
						path: '/discover',
						text: '发现',
						icon: '🔍'
					},
					{
						path: '/market',
						text: 'AI市场',
						icon: '🛒'
					},
					{
						path: '/profile',
						text: '我的',
						icon: '👤'
					}
				]
			}
		},

		computed: {
			showTabBar() {
				// 在登录页面不显示底部导航
				return this.currentPath !== '/login' && this.currentPath !== '/chat-detail' && this.currentPath !==
					'/recharge'
			}
		},

		onShow: function() {
			const token = uni.getStorageSync('token')
			const openid = uni.getStorageSync('openid')
			if(token&&!openid){
				//登陆后绑定
				this.checkWechatEnv('bindLogin')
			}
			
			
		},

		onLaunch: async function() {
			const token = uni.getStorageSync('token')
			if (!token) {
				this.checkWechatEnv('openId')
			}else{
				try {
					const memberRes = await userAPI.getMemberInfo()
					uni.setStorageSync('isMember',memberRes?.data?.memberId)
					if(!memberRes?.data?.openId){
						let query = new URLSearchParams(window.location.search);
						let code = query.get('code');
						let state = query.get('state');
						if(code){
							const res = await wechatAPI.wechatBind({
								code,
								state
							})
						}
					}
				} catch (error) {
					console.error('获取会员信息失败:', error)
				}
			}

		},

		methods: {
			// 检测是否是微信环境
			checkWechatEnv(type) {
				const ua = window.navigator.userAgent.toLowerCase()
				const isWechatEnv = ua.indexOf('micromessenger') > -1
				console.log(ua)

				// 如果是微信环境，进行微信授权
				if (isWechatEnv) {
					this.wechatAuth(type)
				}
			},


			// 微信授权
			async wechatAuth(type) {
				if(uni.getStorageSync('token')){
					return
				}
				// 获取当前页面URL作为回调地址
				const currentUrl = window.location.href


				if (window.location.href.indexOf('code=') == -1 && window.location.href.indexOf('localhost') == -1) {
					try {
						const res = await wechatAPI.wechatUrl({
							type,
							syncRedirect: currentUrl
						})
						const url = res.data.url;
						window.location.href = url
					} catch (error) {
						console.error('获取微信授权URL失败:', error)
					}

				} else {
					// 检查URL中是否已经包含code参数，如果没有则跳转到授权页面
					let query = new URLSearchParams(window.location.search);
					let code = query.get('code');
					let state = query.get('state');
					let pathname = window.location.pathname
					pathname = pathname.endsWith('/') ? pathname : pathname + '/'
					console.log('index.html里的pathname: ', pathname)
					console.log('index.html里的code: ', code)
					console.log('index.html里的code: ', state)
					window.location.hash = "/#/";
					try {
						const res= await wechatAPI.wechatCallBack({
							code,
							state
						})
						// if(type=='openId'){
						// 	res = await wechatAPI.wechatCallBack({
						// 		code,
						// 		state
						// 	})
						// }else{
						// 	res = await wechatAPI.wechatBind({
						// 		code,
						// 		state
						// 	})
						// }
						if (res && res.code == 0) {
							localStorage.setItem('openid', res.data.openid)
							localStorage.setItem('token', res.data.token)
						}else{
							this.checkLoginStatus()
						}
					} catch (error) {
						console.error('微信回调失败:', error)
						this.checkLoginStatus()
					}
				}
			},
			// 检查登录状态
			checkLoginStatus() {
				const token = uni.getStorageSync('token')
				if (!token) {
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}
			},

			// 切换标签页
			switchTab(path) {
				if (this.currentPath !== path) {
					this.currentPath = path
					// 使用 UniApp 的页面跳转
					if (path === '/index') {
						uni.switchTab({
							url: '/pages/index/index'
						})
					} else if (path === '/discover') {
						uni.switchTab({
							url: '/pages/discover/discover'
						})
					} else if (path === '/market') {
						uni.switchTab({
							url: '/pages/market/market'
						})
					} else if (path === '/profile') {
						uni.switchTab({
							url: '/pages/profile/profile'
						})
					}
				}
			}
		}
	}
</script>

<style>
	/* 全局样式 */
	page {
		background-color: #3A3052;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
	}

	img {
		max-width: 100%;
		height: auto;
	}
	.uni-tabbar__label{
		font-size: 20px!important;
	}
	.uni-tabbar{
		height: 80px;
	}

	/* 通用颜色变量 */
	:root {
		--primary-bg: #3A3052;
		--secondary-bg: #4A4062;
		--accent-color: #F0D9B5;
		--light-accent: #F8E7D0;
		--text-primary: #FFFFFF;
		--text-secondary: #8F82A8;
		--text-muted: #A0A0A0;
		--border-color: #52496D;
		--success-color: #4CAF50;
		--warning-color: #FF9800;
		--error-color: #F44336;

		/* 基础字体大小 */
		--font-size-base: 16px;
		--font-size-small: 14px;
		--font-size-xs: 12px;
		--font-size-large: 18px;
		--font-size-xl: 20px;
	}
	.think{
		opacity:0.6;
	}

	/* 通用样式类 */
	.flex {
		display: flex;
	}

	.flex-column {
		flex-direction: column;
	}

	.flex-center {
		justify-content: center;
		align-items: center;
	}

	.flex-between {
		justify-content: space-between;
		align-items: center;
	}

	.text-center {
		text-align: center;
	}

	.rounded {
		border-radius: 8px;
	}

	.shadow {
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	/* 按钮样式 */
	.btn {
		padding: 12px 24px;
		border-radius: 8px;
		border: none;
		font-size: var(--font-size-base);
		font-weight: 500;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.btn-primary {
		background-color: var(--accent-color);
		color: #333;
	}

	.btn-primary:active {
		background-color: #E0C090;
	}

	.btn-secondary {
		background-color: var(--secondary-bg);
		color: var(--text-primary);
	}

	.btn-secondary:active {
		background-color: #3A3052;
	}

	/* 输入框样式 */
	.input {
		padding: 12px 16px;
		border: 1px solid var(--border-color);
		border-radius: 8px;
		background-color: var(--secondary-bg);
		color: var(--text-primary);
		font-size: var(--font-size-base);
	}

	.input:focus {
		outline: none;
		border-color: var(--accent-color);
	}

	/* 卡片样式 */
	.card {
		background-color: var(--secondary-bg);
		border-radius: 12px;
		padding: 16px;
		margin: 8px 0;
	}

	/* 动画 */
	.fade-enter-active,
	.fade-leave-active {
		transition: opacity 0.3s;
	}

	.fade-enter,
	.fade-leave-to {
		opacity: 0;
	}

	.slide-up-enter-active,
	.slide-up-leave-active {
		transition: transform 0.3s;
	}

	.slide-up-enter,
	.slide-up-leave-to {
		transform: translateY(100%);
	}

	/* 底部导航栏 */
	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 50px;
		background-color: #3A3052;
		border-top: 1px solid #52496D;
		display: flex;
		z-index: 1000;
	}

	.tab-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.tab-item:active {
		background-color: rgba(74, 64, 98, 0.3);
	}

	.tab-item.active {
		background-color: rgba(240, 217, 181, 0.1);
	}

	.tab-icon {
		font-size: 22px;
		margin-bottom: 2px;
	}

	.tab-text {
		color: #8F82A8;
		font-size: 14px;
		transition: color 0.3s ease;
	}

	.tab-item.active .tab-text {
		color: #F0D9B5;
	}

	/* 页面内容区域 */
	.page-content {
		padding-bottom: 50px;
	}
</style>